package org.lyimg.com.imgapplication.presenter;

import android.util.Log;

import org.lyimg.com.imgapplication.RetrofitHelper.ImgLoader;
import org.lyimg.com.imgapplication.bean.ImgList;
import org.lyimg.com.imgapplication.view.IimgsView;

import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * Created by liuyong on 2019/1/21.
 */

public class ImgsPresente extends BasePresenter<IimgsView> {

    int page = 1;
    String url;
    ImgLoader mImgLoader = new ImgLoader();

    public ImgsPresente() {
    }

    public void setUrl(String url) {
        this.url = url;
    }

    /**
     * pg =1 为第一页
     *
     * @param pg
     */
    public void getImgs(int pg) {
        String link = "";
        if (pg == 1) {
            page = 1;
            link = url;
        } else {
            if (url.contains("guonei") || url.contains("meinv") || url.contains("gangtai")) {
                link = url + "list_" + page + ".html";
            } else if (url.contains("zh")) {
                link = url + "index_" + page + ".html";
            } else {
                link = url.replace(".html", "") + "/" + page + ".html";
            }
        }
        if (null != weakReference) {
            weakReference.get().showLoadingDialog();
        }
        mImgLoader.getImglists(link).subscribe(new Consumer<List<ImgList>>() {

            @Override
            public void accept(List<ImgList> imgList) throws Exception {
                if (null != weakReference) {
                    weakReference.get().dissLoadingDialog();
                    weakReference.get().notifyImgList(page, imgList);
                    ImgsPresente.this.page++;
                }
            }
        }, new Consumer<Throwable>() {
            @Override
            public void accept(Throwable throwable) throws Exception {
                Log.e("TAG", "error message:" + throwable.getMessage());
                if (null != weakReference) {
                    weakReference.get().dissLoadingDialog();
                    weakReference.get().showError("请求失败");
                }
            }
        });

    }
}
